package com.ys.service.overseas.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.overseas.TosChannelStock;
import com.ys.entity.overseas.TosPurchasePlanItem;
import com.ys.entity.overseas.TosPurchasePlanSon;
import com.ys.entity.sys.TsUserChange;
import com.ys.enume.overseas.TosPurchasePlanSonEnum;
import com.ys.mapper.overseas.TosChannelStockMapper;
import com.ys.mapper.overseas.TosPurchasePlanItemMapper;
import com.ys.mapper.overseas.TosPurchasePlanSonMapper;
import com.ys.service.overseas.TosPurchasePlanItemService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-19
 * @Description: HW采购结算发货
 * @Version: 1.5
 */
@Service("tosPurchasePlanItemService")
public class TosPurchasePlanItemServiceImpl implements TosPurchasePlanItemService {

    private static final Logger logger = LoggerFactory.getLogger(TosPurchasePlanItemServiceImpl.class);
    @Autowired
    private TosPurchasePlanSonMapper tosPurchasePlanSonMapper;

    @Autowired
    private TosChannelStockMapper tosChannelStockMapper;

    @Autowired
    private TosPurchasePlanItemMapper tosPurchasePlanItemMapper;


    /**
     * 结算取消
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R qx(Long id) throws Exception {
        TosPurchasePlanItem tosPurchasePlanItem = new TosPurchasePlanItem().setId(id).queryFirst();
        if (tosPurchasePlanItem == null){
            throw new RuntimeException("HW采购结算单据不存在,请核实后再操作!");
        }
        TosPurchasePlanSon tosPurchasePlanSon = new TosPurchasePlanSon().setId(tosPurchasePlanItem.getPurchasePlanSonId()).queryFirst();
        if (tosPurchasePlanSon == null){
            throw new RuntimeException("HW采购计划单据不存在,请核实后再操作!");
        }
        if (tosPurchasePlanSon.getStatus() != TosPurchasePlanSonEnum.STATUS.PENDINGPAYMENT.value){
            throw new RuntimeException("HW采购结算单据采购状态不是付款待确认,不允许结算取消!");
        }

        tosPurchasePlanSon.setStatus(TosPurchasePlanSonEnum.STATUS.DSCANCEL.value);
        tosPurchasePlanSonMapper.update(tosPurchasePlanSon);

        tosPurchasePlanItem.setStatus(TosPurchasePlanSonEnum.STATUS.DSCANCEL.value);
        tosPurchasePlanItemMapper.update(tosPurchasePlanItem);



        return R.ok("结算取消成功!");
    }

    /**
     * 结算审核
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R sh(Long id) throws Exception {
        TosPurchasePlanItem tosPurchasePlanItem = new TosPurchasePlanItem().setId(id).queryFirst();
        if (tosPurchasePlanItem == null){
            throw new RuntimeException("HW采购结算单据不存在,请核实后再操作!");
        }
        TosPurchasePlanSon tosPurchasePlanSon = new TosPurchasePlanSon().setId(tosPurchasePlanItem.getPurchasePlanSonId()).queryFirst();
        if (tosPurchasePlanSon == null){
            throw new RuntimeException("HW采购计划单据不存在,请核实后再操作!");
        }
        if (tosPurchasePlanSon.getStatus() != TosPurchasePlanSonEnum.STATUS.PENDINGPAYMENT.value){
            throw new RuntimeException("HW采购结算单据采购状态不是付款待确认,不允许结算取消!");
        }

        tosPurchasePlanSon.setStatus(TosPurchasePlanSonEnum.STATUS.READYSHIPMENT.value);
        tosPurchasePlanSonMapper.update(tosPurchasePlanSon);

        String loginUserId = ShiroUtils.getUserId();
        TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
        tosPurchasePlanItem.setAuditingTime(new Date());
        tosPurchasePlanItem.setAuditingUser(tsUserChange.getUserName());
        tosPurchasePlanItem.setStatus(TosPurchasePlanSonEnum.STATUS.READYSHIPMENT.value);
        tosPurchasePlanItemMapper.update(tosPurchasePlanItem);

        return R.ok("结算审核成功!");
    }

    /**
     * 发货取消
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R fhqx(Long id) throws Exception {
        TosPurchasePlanItem tosPurchasePlanItem = new TosPurchasePlanItem().setId(id).queryFirst();
        if (tosPurchasePlanItem == null){
            throw new RuntimeException("HW采购发货单据不存在,请核实后再操作!");
        }
        TosPurchasePlanSon tosPurchasePlanSon = new TosPurchasePlanSon().setId(tosPurchasePlanItem.getPurchasePlanSonId()).queryFirst();
        if (tosPurchasePlanSon == null){
            throw new RuntimeException("HW采购计划单据不存在,请核实后再操作!");
        }
        if (tosPurchasePlanSon.getStatus() != TosPurchasePlanSonEnum.STATUS.READYSHIPMENT.value){
            throw new RuntimeException("HW采购发货单据采购状态不是待发货,不允许发货取消!");
        }

        tosPurchasePlanSon.setStatus(TosPurchasePlanSonEnum.STATUS.FHCANCEL.value);
        tosPurchasePlanSonMapper.update(tosPurchasePlanSon);


        tosPurchasePlanItem.setStatus(TosPurchasePlanSonEnum.STATUS.FHCANCEL.value);
        tosPurchasePlanItemMapper.update(tosPurchasePlanItem);

        return R.ok("发货取消成功!");
    }

    /**
     * 订单导入追踪编码
     * @param rows
     * @param menuId
     * @return
     * @throws Exception
     */
    @Override
    public R importInfoDd(String rows, Long menuId) throws Exception {
        logger.info("订单导入追踪编码的数据：\n"+rows);

        try {
            StringBuilder errorMsg = new StringBuilder();
            //获取导入数据
            JSONArray detailList = JSON.parseArray(rows);
            for(int i=0;i<detailList.size();i++) {
                JSONObject info = detailList.getJSONObject(i);
                Map<String, Object> infoMap = new HashMap<>();
                for (String key : info.keySet()) {
                    infoMap.put(key, info.get(key));
                }
                //验证追踪编号
                if(info.get("tracingCode")==null || "".equals(info.get("tracingCode"))){
                    logger.error("第"+(i+1)+"条数据追踪编号为空");
                    errorMsg.append("第"+(i+1)+"条数据追踪编号为空\n");
                    continue;
                }
                //验证订单
                if(info.get("orderCode")==null || "".equals(info.get("orderCode"))){
                    logger.error("第"+(i+1)+"条数据订单为空");
                    errorMsg.append("第"+(i+1)+"条数据订单为空\n");
                    continue;
                }
                List<TosPurchasePlanSon> tosPurchasePlanSonList = new TosPurchasePlanSon().setOrderCode(info.get("orderCode").toString())
                        .addLeftJoin("TOS_PurchasePlanItem B ON B.PurchasePlanSonId = A.id")
                        .where("B.Status = 4")
                        .queryList();
                if (tosPurchasePlanSonList.size() == 0){
                    errorMsg.append("第"+(i+1)+"条数据，未查询到待发货状态下订单号:"+info.get("orderCode") + "的数据\n");
                    continue;
                }
                for (TosPurchasePlanSon tosPurchasePlanSon : tosPurchasePlanSonList){
                    tosPurchasePlanSon.setStatus(TosPurchasePlanSonEnum.STATUS.ACCOMPLISH.value);
                    tosPurchasePlanSonMapper.update(tosPurchasePlanSon);

                    TosPurchasePlanItem tosPurchasePlanItem = new TosPurchasePlanItem().setPurchasePlanSonId(tosPurchasePlanSon.getId()).queryFirst();
                    tosPurchasePlanItem.setTracingCode(info.get("tracingCode").toString());
                    tosPurchasePlanItem.setStatus(TosPurchasePlanSonEnum.STATUS.ACCOMPLISH.value);
                    tosPurchasePlanItemMapper.update(tosPurchasePlanItem);
                }
            }
            if(errorMsg.length()>0){
                return R.ok(errorMsg.toString());
            }
        }catch (Exception e){
            logger.error("导入出错：",e.getMessage(),e);
            return R.error("导入出错,请稍后重试!");
        }
        return R.ok("导入成功！");
    }


    /**
     * 商品编码导入追踪编码
     * @param rows
     * @param menuId
     * @return
     * @throws Exception
     */
    @Override
    public R importInfoSp(String rows, Long menuId) throws Exception {
        logger.info("商品编码导入追踪编码的数据：\n"+rows);

        try {
            StringBuilder errorMsg = new StringBuilder();
            //获取导入数据
            JSONArray detailList = JSON.parseArray(rows);
            for(int i=0;i<detailList.size();i++) {
                JSONObject info = detailList.getJSONObject(i);
                Map<String, Object> infoMap = new HashMap<>();
                for (String key : info.keySet()) {
                    infoMap.put(key, info.get(key));
                }
                //验证追踪编号
                if(info.get("tracingCode")==null || "".equals(info.get("tracingCode"))){
                    logger.error("第"+(i+1)+"条数据追踪编号为空");
                    errorMsg.append("第"+(i+1)+"条数据追踪编号为空\n");
                    continue;
                }
                //验证商品编码
                if(info.get("code")==null || "".equals(info.get("code"))){
                    logger.error("第"+(i+1)+"条数据商品编码为空");
                    errorMsg.append("第"+(i+1)+"条数据商品编码为空\n");
                    continue;
                }
                List<TosPurchasePlanSon> tosPurchasePlanSonList = new TosPurchasePlanSon().setCode(info.get("code").toString())
                        .addLeftJoin("TOS_PurchasePlanItem B ON B.PurchasePlanSonId = A.id")
                        .where("B.Status = 4")
                        .queryList();
                if (tosPurchasePlanSonList.size() == 0){
                    errorMsg.append("第"+(i+1)+"条数据，未查询到待发货状态下商品编码:"+info.get("code") + "的数据\n");
                    continue;
                }
                for (TosPurchasePlanSon tosPurchasePlanSon : tosPurchasePlanSonList){
                    tosPurchasePlanSon.setStatus(TosPurchasePlanSonEnum.STATUS.ACCOMPLISH.value);
                    tosPurchasePlanSonMapper.update(tosPurchasePlanSon);

                    TosPurchasePlanItem tosPurchasePlanItem = new TosPurchasePlanItem().setPurchasePlanSonId(tosPurchasePlanSon.getId()).queryFirst();
                    tosPurchasePlanItem.setTracingCode(info.get("tracingCode").toString());
                    tosPurchasePlanItem.setStatus(TosPurchasePlanSonEnum.STATUS.ACCOMPLISH.value);
                    tosPurchasePlanItemMapper.update(tosPurchasePlanItem);
                }
            }
            if(errorMsg.length()>0){
                return R.ok(errorMsg.toString());
            }
        }catch (Exception e){
            logger.error("导入出错：",e.getMessage(),e);
            return R.error("导入出错,请稍后重试!");
        }
        return R.ok("导入成功！");
    }


    /**
     * 批量导入
     * @param id
     * @param tracingCode
     * @param commodityProperty
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R dr(Long id, String tracingCode, String commodityProperty, String orderCode) throws Exception {
        if (commodityProperty.equals("0")){
            //订单
            List<TosPurchasePlanSon> tosPurchasePlanSonList = new TosPurchasePlanSon().setOrderCode(orderCode)
                    .queryList();
            for (TosPurchasePlanSon tosPurchasePlanSon : tosPurchasePlanSonList){
                tosPurchasePlanSon.setStatus(TosPurchasePlanSonEnum.STATUS.ACCOMPLISH.value);
                tosPurchasePlanSonMapper.update(tosPurchasePlanSon);

                TosPurchasePlanItem tosPurchasePlanItem = new TosPurchasePlanItem().setPurchasePlanSonId(tosPurchasePlanSon.getId()).queryFirst();
                tosPurchasePlanItem.setTracingCode(tracingCode);
                tosPurchasePlanItem.setStatus(TosPurchasePlanSonEnum.STATUS.ACCOMPLISH.value);
                tosPurchasePlanItemMapper.update(tosPurchasePlanItem);
            }
        }else {
            //商品
            TosPurchasePlanItem tosPurchasePlanItem = new TosPurchasePlanItem().setId(id).queryFirst();
            tosPurchasePlanItem.setTracingCode(tracingCode);
            tosPurchasePlanItem.setStatus(TosPurchasePlanSonEnum.STATUS.ACCOMPLISH.value);
            tosPurchasePlanItemMapper.update(tosPurchasePlanItem);

            List<TosPurchasePlanSon> tosPurchasePlanSonList = new TosPurchasePlanSon().setId(tosPurchasePlanItem.getPurchasePlanSonId())
                    .queryList();
            for (TosPurchasePlanSon tosPurchasePlanSon : tosPurchasePlanSonList){
                tosPurchasePlanSon.setStatus(TosPurchasePlanSonEnum.STATUS.ACCOMPLISH.value);
                tosPurchasePlanSonMapper.update(tosPurchasePlanSon);

            }
        }
        return R.ok("导入成功！");
    }
}
